package com.aisile.student.service.impl;

import com.aisile.model.student.dtos.StudentListDto;
import com.aisile.model.student.pojos.Student;
import com.aisile.model.base.vos.R;
import com.aisile.model.student.vos.StudentListVo;
import com.aisile.student.mapper.StudentMapper;
import com.aisile.student.service.StudentService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther:yry
 * @Date:2024/6/19 0019
 * @VERSON:1.0
 */
@Service
@SuppressWarnings("ALL")
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public R findAllByPage(StudentListDto dto) {
        if (dto == null) {
            return R.fail("对象为空！");
        }
        // 需要对 分页参数 进行处理  以及  like 处理
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getSize() == null) {
            dto.setSize(2);
        }
        // 需要对page 进行替换算法
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        if (dto.getName() != null && !"".equals(dto.getName())) {
            dto.setName("%" + dto.getName() + "%");
        }
        // 调用查询 获取参数 然后拼接参数  返回
        List<StudentListVo> list = studentMapper.findAllByPage(dto);
        Integer total = studentMapper.findCountByPage(dto);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("rows", list);
        resultMap.put("total", total);
        return R.ok(resultMap);
    }

    @Override
    public void saveStudents(Integer teacherId, List<Student> list) {
        //delete from where id in (1,2,3,4)
        if (list != null && list.size() > 0) {
            // 不建议使用当前方式
            list.stream().forEach(x -> {
                x.setTid(teacherId);
                studentMapper.insert(x);  // jdbc 1. 开启链接  2.发送sql 3.执行sql 4.关闭链接
                // 1. 使用连接池    2. 使用xml方式 进行批量删除
            });
        }
    }

    @Override
    public R findStudentNumByTid(Integer id) {
        if (id == null) {
            return R.fail("id不能为空");
        }
        Integer num = studentMapper.selectCount(Wrappers.<Student>lambdaQuery().eq(
                Student::getTid, id
        ));
        return R.ok(num);
    }

    @Override
    public void deleteStudentsbyTid(Integer id) {
        studentMapper.delete(
                Wrappers.<Student>lambdaQuery().eq(
                        Student::getTid,id
                )
        );
    }

    @Override
    public List<Student> getStudentByTid(Integer id) {
        return studentMapper.selectList(
                Wrappers.<Student>lambdaQuery().eq(
                        Student::getTid,id
                )
        );
    }


}
